import Config from "./Config.js";
import {arrAsubB} from "./ToolMethods.js";

let t, timers = [], curr, prepareTimer = [], slowTimer = 1, index = 0;

export default class Timer {
  static start() {
    if ( t )
      return;
    t = setInterval( function(){
      if ( slowTimer !== 1 ){
        if ( index++ % slowTimer !== 0 ){
          return;
        }
      }
      timers = prepareTimer.concat( timers );
      prepareTimer.length = 0;
      for ( curr = timers.length - 1; curr >= 0; curr-- ){
        if ( timers[ curr ].state === 'stop' ){
          continue;
        }
        timers[ curr ]();
        //if ( timers[ curr ].state === 'stop' ){
        //timers[ curr ].state = 'destory';
        //timers.splice( curr, 1 );
        //}
      }

    }, Config.fps * slowTimer );
  }
  static clean() {
    const removing = []
    for ( ; curr >= 0; curr-- ){
      if ( timers[ curr ]() === 'done' ){
        removing.push(timers[ curr ])
        // timers.splice( i, 1 );
      }
    }
    arrAsubB(timers, removing)
  }
  static push(fn) {
    timers[ timers.length ] = fn;
    return fn;
  }
  static unshift(fn) {
    return prepareTimer.unshift( fn );  //保持同步, 不然可能会出现A添加进了timer， 而B没有. 好基友永远不分开.
  }
  static checkZindex(fn) {
    let j, k, oldFn;
    for ( let i = 0, c; c = timers[ i++ ]; ){
      if ( c === fn ){
        j =  i - 1;
      }else if ( c.zIndex ){
        k = i - 1;
        oldFn = c;
      }
    }
    if ( j > k ){
      timers[ j ] = oldFn;
      timers[ k ] = fn;
    }
  }
  static stop() {
    Timer.clean();
    clearInterval( t );
    t = null;
  }
  static empty() {
    timers.length = 0;
  }
  static slow(timer) {
    Timer.stop()
    slowTimer = 3;
    Timer.start();
    setTimeout( function(){
      Timer.stop();
      slowTimer = 1;
      Timer.start();
    }, timer )
  }
  static normal() {
    slowTimer = 1;
  }
  static add(fn) {
    fn.state = 'normal';

    const start = function(){
      if ( fn.state === 'normal' ){
        Timer.unshift( fn );
        fn.state = 'add';
      }

      else if ( fn.state === 'stop' ){
        fn.state = 'add';
      }

    }

    const stop = function(){
      fn.state = 'stop';
    }

    return {start, stop}
  }
}

